package com.movie.music;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.facebook.react.bridge.ActivityEventListener;
import com.movie.R;

import java.util.ArrayList;
import java.util.List;

public class MusicActivity extends AppCompatActivity  {
    private Context mContext;
    private static final int REQUEST_PERMISSION = 0;
    private List<Song> songList = new ArrayList<Song>();
    ListView listView;
    Button confirmBtn;
    MusicAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_activity);
        //getMusic();
        confirmBtn = (Button)findViewById(R.id.confirm_btn);
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //数据是使用Intent返回
                Intent intent = new Intent();
                //把返回数据存入Intent
                System.out.println("-------------");
                System.out.println("****"+adapter.selSong.getTitle());
                Toast.makeText(MusicActivity.this, adapter.selSong.toString(), Toast.LENGTH_LONG).show();
                intent.putExtra("result", adapter.selSong.toString());
                //设置返回数据
                MusicActivity.this.setResult(200, intent);
                //关闭Activity
                MusicActivity.this.finish();
            }
        });

        listView = (ListView)findViewById(R.id.list_view);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                if(arg2>=0){
                    Song song = songList.get(arg2);
                    //Toast.makeText(MusicActivity.this, song.getTitle()+"  "+song.getUrl(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            int hasWritePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int hasReadPermission = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);

            List<String> permissions = new ArrayList<String>();

            //申请权限
            if (hasReadPermission != PackageManager.PERMISSION_GRANTED) {
                //Toast.makeText(MusicActivity.this, "读的权限", Toast.LENGTH_LONG).show();
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);

            } else { // 有权限
                //Toast.makeText(MusicActivity.this, "呵呵", Toast.LENGTH_LONG).show();
//              preferencesUtility.setString("storage", "true");
                //getMusic();
                setListData();
            }

            if (!permissions.isEmpty()) {
                //Toast.makeText(MusicActivity.this, "允许1", Toast.LENGTH_LONG).show();
//              requestPermissions(permissions.toArray(new String[permissions.size()]), REQUEST_CODE_SOME_FEATURES_PERMISSIONS);

                ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                        REQUEST_PERMISSION);
            }
        }

    }
    public void setListData(){
        songList = getMusic();
        adapter = new MusicAdapter(this,R.layout.music_item,songList);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION: {
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MusicActivity.this, "嘎嘎", Toast.LENGTH_LONG).show();
                        setListData();
                        System.out.println("Permissions --> " + "Permission Granted: " + permissions[i]);
                    } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        Toast.makeText(MusicActivity.this, "tttt", Toast.LENGTH_LONG).show();
                        System.out.println("Permissions --> " + "Permission Denied: " + permissions[i]);
                    }
                }
            }
            break;
            default: {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }

    public List<Song> getMusic(){
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        List<Song> musicList = new ArrayList<>();
        if(cursor.moveToFirst()){
            for(int i = 0; i <cursor.getCount();i++) {
                Song m = new Song();
                long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                System.out.println("----"+title);
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
                String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                long album_id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                int ismusic = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));

                if (ismusic != 0 && duration / (500 * 60) >= 1) {
                    m.setId(id);
                    m.setTitle(title);
                    m.setArtist(artist);
                    m.setDuration(duration);
                    m.setSize(size);
                    m.setUrl(url);
                    m.setAlbum(album);
                    m.setAlbum_id(album_id);
                    musicList.add(m);
                }
                cursor.moveToNext();
            }
        }
        return musicList;


    }

}
